import json
import re

from django import http
from django.shortcuts import render
from django.views import View

from apps.address.models import Address
from utils import constants
from utils.response_code import RETCODE


class AddressView(View):
    def get(self,request):
        addresses = Address.objects.filter(is_deleted=False)
        context={
            'username':request.user.username,
            'addresses':addresses
        }
        return render(request,'user_address.html',context)

    def post(self, request):
        """实现新增地址逻辑"""
        # 判断地址最多有20个
        count = request.user.addresses.count()
        # print('----------1,',request.user)
        # print(count)
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '次数不能超过8次'})

        # 接收参数
        json_dict = json.loads(request.body.decode())  # 取出body里面的json数据
        receiver = json_dict.get('receiver')
        place = json_dict.get('place')
        phone = json_dict.get('phone')

        # 校验参数
        if not all([receiver, place, phone,]):
            return http.JsonResponse('缺少必传参数')
        # 校验手机号
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return http.JsonResponse('手机号输入有误')

        # 保存信息
        try:
            address = Address.objects.create(
                user=request.user,
                receiver=receiver,
                place=place,
                phone=phone,
            )
            # 设置默认地址
            # if not request.user.default_address_id:
            #     # print('---------------if')
            #     request.user.default_address_id = address.id
            #     # print('-----------save出错',)
            #     request.user.save()
            #     # print('-----------3,',request.user)
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

    # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            'id': address.id,
            'receiver': address.receiver,
            'place': address.place,
            'phone': address.phone,
        }
        print('添加成功')
        # 返回响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '新增收货地址成功', 'address': address_dict})
        # return render(request,'user_address.html',address_dict)

    def delete(self,request):
        a_id = int(request.body.decode()[3:])
        address = Address.objects.get(id=a_id)
        if not (address and address.user == request.user):
            return http.HttpResponseBadRequest('非法操作')

        try:
            # 将逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            return http.JsonResponse({"code":RETCODE.DBERR,'errmsg':'删除地址失败'})

        return http.JsonResponse({"code":RETCODE.OK,'errmsg':'删除地址成功'})
